package io.renren.modules.app.wx;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;  
import okhttp3.Response;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class WeChatUtil {  
  
    private static final String APP_ID = WxAppIdEnum.TAI_HUA_MP.getAppId();
    private static final String APP_SECRET = WxAppIdEnum.TAI_HUA_MP.getSecret();

    /**
     * todo 记得更新保存token
     * access_token的有效期通常较短（一般为7200秒），需要合理管理access_token的获取和存储
     * @return
     * @throws Exception
     */
    public static String getAccessToken() throws Exception {  
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + APP_ID + "&secret=" + APP_SECRET;  
        OkHttpClient client = new OkHttpClient();  
        Request request = new Request.Builder().url(url).get().build();  
        Response response = client.newCall(request).execute();
        log.info("获取微信token：{}",JSONUtil.toJsonStr(response));
        // 解析响应，提取access_token  
        // 这里只是示例，具体解析需要根据你的响应格式进行  
        return "获取的access_token";  
    }


    /**
     * 微信消息模版发送
     * @param messageVo
     * @param token
     * @param openId
     * @return
     */
    public static JSONObject sendMsg(String content1, String token, String openId) {
        String requestUrl = " https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="  + token;
        Map<String,Object> content=new HashMap<>();
        JSONObject data = JSONUtil.createObj();
        data.put("first",new JSONObject().put("value","微信公众号消息"));
        data.put("keyword1",new JSONObject().put("value",content1));
//        data.put("keyword2",new JSONObject().put("value",messageVo.getTKeyword2()));
//        data.put("keyword3",new JSONObject().put("value",messageVo.getTKeyword3()));
//        data.put("keyword4",new JSONObject().put("value",messageVo.getTKeyword4()));
//        data.put("remark",new JSONObject().put("value",messageVo.getTRemark()));

        content.put("touser",openId);
//        content.put("url",messageVo.getTUrl());
        content.put("template_id","jbgHt8W8RNpRN2KZwvAMty40iiZU2sa9dqnFXOsCvqw");
        content.put("data",data);
        String resp = HttpUtil.post(requestUrl,JSONUtil.parseFromMap(content).toString());
        System.out.println(content.toString());
        System.out.println(JSONUtil.parseFromMap(content));
        JSONObject result = JSONUtil.parseObj(resp);
        System.out.println("发送消息:" + resp);
        return result;
    }




}